const app = getApp()

Page({
  data: {
    imgWidth: 0,
    imgHeight: 0,
    flags: {},
  },

  onLoad: function (options) {
    wx.showLoading({
      title: '图片生成中...',
      icon: 'loading',
    })

    // 获取答对数量
    var num = options.rightNum
    var dengji = 'A';

    if (num == 0) {
      dengji = 'D'
    } else if (num == 1 || num == 2 || num == 3) {
      dengji = 'C'
    } else if (num == 4 || num == 5 || num == 6) {
      dengji = 'B'
    } else if (num == 7 || num == 8 || num == 9) {
      dengji = 'A'
    } else if (num == 10) {
      dengji = 'S'
    }

    this.getConfig(dengji)
  },

  getConfig: function (dengji) {
    var that = this
    wx.request({
      url: app.globalData.url + 'config/v/' + app.globalData.version,
      success: function (res) {
        that.setData({
          flags: res.data.data
        })
        that.getImageUrl(dengji)
      }
    })
  },

  getImageUrl: function (dengji) {
    var that = this
    wx.request({
      url: app.globalData.url + 'get_img_src?v=' + app.globalData.version + '&type=' + dengji,
      success: function (res) {
        that.createImg(res.data)
      }
    })
  },

  onShareAppMessage: function (n) {
    return {
      title: "快来测试你的脑力等级吧",
      path: "/pages/index/index",
    };
  },

  // 将图片绘制在canvas中
  createImg: function (imgBg) {
    var that = this
    var shareflag = that.data.flags.shareflag
    var userInfo = app.globalData.userInfo
    if (!userInfo) {
      userInfo = wx.getStorageSync('brainpowerUserInfo');
    }
    var erweima = '/images/ewm.png'
    var canvas = wx.createCanvasContext('canvas')

    // 获取图片宽高
    wx.getImageInfo({
      src: imgBg,
      success: function (res) {
        var img_w = res.width / 1.5
        var img_h = res.height / 1.5

        that.setData({
          imgWidth: img_w,
          imgHeight: img_h,
        })
        canvas.drawImage(res.path, 0, 0, img_w, img_h);
        if (shareflag) {
          canvas.drawImage(erweima, img_w * 0.22, img_h * 0.76, img_w * 0.22, img_w * 0.22);
        }
        canvas.setFontSize(20)
        var len = that.getBLen(userInfo.nickName) * 10
        canvas.fillText(userInfo.nickName, (img_w - len) / 2, img_h * 0.41);

        wx.downloadFile({
          url: userInfo.avatarUrl,
          success: res => {
            canvas.drawImage(res.tempFilePath, img_w * 0.39, img_w * 0.28, img_w * 0.23, img_w * 0.23);
            canvas.draw()
            that.setT()
          },
          fail: function (e) {
            console.log(e)
            canvas.draw()
            that.setT()
          }
        })
      },
      fail: function (e) {
        console.log(e)
      }
    })
  },

  // 超时画图
  setT: function () {
    var that = this
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        success: function (res) {
          that.setData({
            imagePath: res.tempFilePath,
          })
          wx.hideLoading()
        },
        fail: function (res) {
          wx.hideLoading()
          console.log(res)
        }
      })
    }, 300)
  },

  // 获取字节长度
  getBLen: function (str) {
    if (str == null) return 0;
    if (typeof str != "string") {
      str += "";
    }
    return str.replace(/[^\x00-\xff]/g, "ab").length;
  },

  //点击图片进行预览
  previewImg: function (e) {
    var img = this.data.imagePath
    wx.previewImage({
      current: img,
      urls: [img]
    })
  },

  // 保存图片
  toSave: function () {
    var that = this;
    wx.showLoading({
      mask: true,
      title: "保存中"
    })
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success: (res) => {
        wx.hideLoading()
        wx.showModal({
          title: "保存成功",
          content: "图片已经保存到手机相册",
          showCancel: "false"
        })
      },
      fail: function (error) {
        wx.hideLoading();
        wx.openSetting({
          success(settingdata) {
            if (settingdata.authSetting['scope.writePhotosAlbum']) {
              console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
            } else {
              console.log('获取权限失败，给出不给权限就无法正常使用的提示')
            }
          }
        })
      }
    })
  },
})